package cn.zcy.untils;
import io.jsonwebtoken.*;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt 鉴权验证
 */
public class JWTUtils {
    // 使用 Base64 编码的公钥和私钥字符串 PUBLIC_KEY_STRING
    private static final String PUBLIC_KEY_STRING = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy4blzpFxMRctIAF8b0j83a6T0lqd9xPr9hMtURhIzIU1PpBYyVl4Gh81XR6g1F0NxwBQ58LpRnUTV5kmAK4cEvJe8Bh2P/bJ/w8R9FuAuc+fiqNpG71wvkesuR4s/N+ijA7IhhNozfZnR+WTanUreLqxXckCD+ImZrKBTHWvgDbzEBUQPJCf6lhgb5P6Yc+uxYQMx2ItqpKaTgeCMz5sIopHnrV7erSdQt7UK+JfgH8CDCYgSZzOWLJR1DuO0shALga3rEpNL6MXiIrGEsDuT+EhADp4hy6wJ7f42/cB5WLgk0jHUSFSwhrw0o2noABexXufw8+C1pNqEQSNc0iAsQIDAQAB"; //公钥
    private static final String PRIVATE_KEY_STRING = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLhuXOkXExFy0gAXxvSPzdrpPSWp33E+v2Ey1RGEjMhTU+kFjJWXgaHzVdHqDUXQ3HAFDnwulGdRNXmSYArhwS8l7wGHY/9sn/DxH0W4C5z5+Ko2kbvXC+R6y5Hiz836KMDsiGE2jN9mdH5ZNqdSt4urFdyQIP4iZmsoFMda+ANvMQFRA8kJ/qWGBvk/phz67FhAzHYi2qkppOB4IzPmwiikeetXt6tJ1C3tQr4l+AfwIMJiBJnM5YslHUO47SyEAuBresSk0voxeIisYSwO5P4SEAOniHLrAnt/jb9wHlYuCTSMdRIVLCGvDSjaegAF7Fe5/Dz4LWk2oRBI1zSICxAgMBAAECgg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e3USIWKwgEQz73xqT5pkH4mHSdPyDDAn8f44YEzoYrxyFJpNg2hNXVeaCkouIyi+NCKL+p0knAvtodgJ1nnN2bbfCHlVUvkAMkJ5HxDjJN4utNADSLM9aSYoWZU44G6TtvpRbvk=";   //私钥

    // 生成 JWT token
    public String generateToken(Map<String, Object> claims) throws Exception {
        PrivateKey privateKey = getPrivateKey(PRIVATE_KEY_STRING);
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1天有效期
                .signWith(SignatureAlgorithm.RS256, privateKey) // 使用私钥签名
                .compact();
    }

    // 验证 JWT token
    public boolean validateToken(HzArrayElement hzArrayElement) throws Exception {
        PublicKey publicKey = getPublicKey(PUBLIC_KEY_STRING);
        Claims body = Jwts.parser()
                .setSigningKey(publicKey) // 使用公钥验证
                .parseClaimsJws(hzArrayElement.getToken())
                .getBody();
        HzAudience hzAudience = hzArrayElement.getHzAudience();
        if (hzAudience.getRegistAccount().equals(body.get("registAccount", String.class)) && hzAudience.getName().equals(body.get("name", String.class)) && hzAudience.getEmail().equals(body.get("email", String.class))) {
            return true;
        } else {
            return false;
        }
    }

    // 从 Base64 字符串获取私钥
    private PrivateKey getPrivateKey(String base64PrivateKey) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(base64PrivateKey);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(spec);
    }

    // 从 Base64 字符串获取公钥
    private PublicKey getPublicKey(String base64PublicKey) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(base64PublicKey);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(spec);
    }

    public static void main(String[] args) throws Exception {
        JWTUtils jwtUtils = new JWTUtils();
        Map<String, Object> claims = new HashMap<>();
        claims.put("registAccount", "136****8882");
        claims.put("name", "施*轩");
        claims.put("email", "871******@qq.com");
        String s = jwtUtils.generateToken(claims);
        System.out.println("s = " + s);
    }

}
